<?php
namespace app\index\controller;
use app\common\controller\Common;
use app\index\model\Category;
use app\index\model\Collect;
use app\index\model\Question;
use app\index\model\Reply;
use app\index\model\Vercode;
use app\index\model\Zan;
use think\Controller;
use think\Db;
use think\Loader;
class Jie extends Common
{
    public function index()
    {
        // Db::query("")

        // Db::transaction(function(){

        //     Db::table('think_user')->find(1);
        //     Db::table('think_user')->delete(1);
        // });

        Db::startTrans();
        try{
            Db::table('test')->insert(['tname'=>'小花1']);
            Db::table('test')->insert(['tname'=>'小花2']);
            Db::table('test')->insert(['tname'=>'小花3']);

            // Db::rollback();
            // 提交事务
            Db::commit();    
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }


        exit;


        // var_dump(url('index/jie/index',['qid'=>3]));
        $qid = input('qid');
        
        // $qid = intval($qid);

        // $sql = "select * from fly_question where qid=".$qid;

        // var_dump($sql);

        // var_dump($qid);exit;

        $uid  = session('uid') ? session('uid') : 'null';

        // 联表查询 数据 
        $question = Db::table('fly_question')
        ->alias('t1')
        ->field('t1.*,t2.face,t2.nickname,t3.cname,t4.coid')
        ->join('fly_user t2','t1.uid = t2.uid')
        ->join('fly_category t3','t1.cid=t3.cid')
        ->join('fly_collect t4','t1.qid=t4.qid and t4.uid='.$uid,'LEFT')
        ->where(['t1.qid'=>$qid])
        ->find();

        if(!$question){
            $this->error("非法请求，没有对应的帖子");
        }

        Question::get($qid)->setInc('view_num');

        // 转json
        $question['ext'] = json_decode($question['ext'],true);



        // 联表查询 数据 
        $answer = Db::table('fly_reply')
        ->alias('t1')
        ->field('t1.*,t2.face,t2.nickname,t3.zid')
        ->join('fly_user t2','t1.uid = t2.uid')
        ->join('fly_zan t3','t1.rid=t3.rid and t3.uid='.$uid,'LEFT')
        ->where(['t1.qid'=>$qid])
        ->order('t1.rid desc')
        ->select();

        $category = Db::table('fly_category')->order('sort desc')->cache(true,86400)->select();




        $hotQues = Db::table('fly_question')->order('reply_num desc')->limit(10)->cache(true,3600)->select();

        $this->assign('hotQues',$hotQues);
        $this->assign('category',$category);
        $this->assign('ques',$question);
        $this->assign('answer',$answer);
        $this->assign('title',$question['title']);
        return $this->fetch();
    }
    public function add()
    {

        // $res = Db::table('fly_category')->select();

        // var_dump($res);

        $cateGory = Category::all();

        // 从数据库中随机获取 一个问题，把答案存储在session;
        
        $question = (new Vercode)->getRandOne();
        // 分配变量
        $this->assign('question',$question);

        // var_dump($cateGory);

        $this->assign('category',$cateGory);
        $this->assign('title',"我来水一下");
        return $this->fetch();
    }

    public function add_post()
    {
        $data = input('post.');

        $validate = Loader::validate('Jie');

        // $data['phone']= 516514654165352165;

        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $res =  (new Question)->addQuestion($data);

        //  3  把数据增加到数据 
        //  
        if($res){
            $this->success("发布成功",url('index/jie/index',['qid'=>$res]));
        }else{
            $this->error("发布失败");
        }
    }

    public function upload()
    {

        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'tie_img');
            if($info){

                $face = config('site.root_path')."tie_img/".date("Ymd")."/".$info->getFilename();

                $data = [
                    'code'=>0,
                    'msg'=>'上传成功',
                    'data'=>[
                        'src'=>$face,
                        'title'=>'图片名称'
                    ]
                ];

                exit(json_encode($data));

                // $this->error('上传成功');
            }else{

                $this->success($file->getError());
            }
        }
    }

    public function reply()
    {
        // if(!session('uid')){
        //     $this->error("你还没有登录，请先登录！");
        // }
        $data = input('post.');

        $validate = Loader::validate('reply');

        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['uid'] = session('uid');

        $data['ctime'] = time();

        $res = (new Reply)->data($data)->save();


        Question::get($data['qid'])->setInc('reply_num');

        if($res){
            $this->success("回贴成功");
        }else{
            $this->error("回贴失败");
        }
    }

    public function collect()
    {
        // if(!session('uid')){
        //     $this->error("你还没有登录，请先登录！");
        // }
        $qid = input('post.qid');

        $res = Collect::get(['qid'=>$qid,'uid'=>session('uid')]);

        if($res){

            Collect::destroy(['qid'=>$qid,'uid'=>session('uid')]);

            $this->success("取消成功");

        }else{

            (new Collect)->data(['qid'=>$qid,'uid'=>session('uid'),'ctime'=>time()])->save();

            $this->success("收藏成功");

        }

        // if($res){
        //     $this->success("回贴成功");
        // }else{
        //     $this->error("回贴失败");
        // }
    }

    public function zan()
    {
        // if(!session('uid')){
        //     $this->error("你还没有登录，请先登录！");
        // }
        $rid = input('post.rid');

        $res = Zan::get(['rid'=>$rid,'uid'=>session('uid')]);

        if($res){

            Zan::destroy(['rid'=>$rid,'uid'=>session('uid')]);

            Reply::get($rid)->setDec('zan_num');

            $this->success("取消成功");

        }else{

            (new Zan)->data(['rid'=>$rid,'uid'=>session('uid'),'ctime'=>time()])->save();

            Reply::get($rid)->setInc('zan_num');

            $this->success("点赞成功");

        }
    }



}
